package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 设备管理Service业务层处理
 *
 * @author JQ
 * @date 2025-08-03
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 华为云物联网客户端
    @Autowired
    private IoTDAClient client;

    @Override
    public void deleteDevice(String iotId) {
        // 删除IoTDA平台上的设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("调用IoT平台设备删除失败");
        }
        // 删除本地存储的设备
        remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowVo> queryServiceProperties(String iotId) {
        // 1、调用华为云IOT，查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);

        // 2、查询不到，返回空
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            return Collections.emptyList();
        }

        // 3、转换成Vo数据
        // 3.1 获取属性集合信息
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        // 3.2 日期时区转换
        LocalDateTime eventTimeInfo = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        // 3.3 Vo封装
        List<DeviceShadowVo> vos = new ArrayList<>();
        jsonObject.forEach((key, value) -> {
            DeviceShadowVo vo = DeviceShadowVo.builder()
                    .functionId(key)
                    .value(value)
                    .eventTime(eventTimeInfo)
                    .build();
            vos.add(vo);
        });
        return vos;
    }

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceDetail(String iotId) {
        // 查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }

        // 调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        // 属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceVo.setActiveTime(activeTime);
        }

        return deviceVo;
    }

    /***
     * 设备注册
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        // 1、设备名称不能重复
        Long deviceNameCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName()));
        if (deviceNameCount >= 1) {
            // 抛出异常
            throw new BaseException("当前设备名称已存在！");
        }

        // 2、设备唯一标识不能重复
        Long nodeCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getNodeId, dto.getNodeId()));
        if (nodeCount >= 1) {
            // 抛出异常
            throw new BaseException("当前设备标识已存在！");
        }

        // 3、同一位置不能绑定相同的产品
        Long sameCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(dto.getBindingLocation()), Device::getBindingLocation, dto.getBindingLocation())
                .eq(ObjectUtil.isNotEmpty(dto.getLocationType()), Device::getLocationType, dto.getLocationType())
                .eq(ObjectUtil.isNotEmpty(dto.getPhysicalLocationType()), Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(ObjectUtil.isNotEmpty(dto.getProductKey()), Device::getProductKey, dto.getProductKey())
        );
        if (sameCount >= 1) {
            // 抛出异常
            throw new BaseException("当前位置已存在相同设备！");
        }

        // 4、调用华为云IOT平台注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        AuthInfo authInfobody = new AuthInfo();
        authInfobody.withSecret(UUID.randomUUID().toString().replace("-", ""));
        body.withAuthInfo(authInfobody);
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());
        request.withBody(body);

        // 调用华为云
        AddDeviceResponse response = client.addDevice(request);
        String deviceId = response.getDeviceId();

        // 5、将数据写入到本地  dto->Device
        Device device = BeanUtil.toBean(dto, Device.class);
        // 设备ID
        device.setIotId(deviceId);
        device.setSecret(authInfobody.getSecret());
        save(device);
    }

    /**
     * 查询物联网产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 同步物联网设备列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网设备信息,同步失败");
        }
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        device.setCreateTime(DateUtils.getNowDate());
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param deviceDto 设备
     * @return 结果
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {
        // 调用华为云IoT平台修改设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(deviceDto.getDeviceName());
        request.setBody(body);
        try {
            client.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("调用IoT平台修改设备失败");
        }
        // 修改本地存储的设备
        // deviceDto->Device
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        try {
            updateById(device);
        } catch (Exception e) {
            throw new BaseException("该老人/位置已绑定该类型的设备，请重新选择绑定位置");
        }
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(String ids) {
        return deviceMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除设备管理信息
     *
     * @param iotId 设备管理主键
     * @return 结果
     */
    @Override
    public void deleteDeviceById(String iotId) {

    }

    /**
     * 查询产品信息
     *
     * @param productKey 产品标识
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        // 1、创建请求参数
        ShowProductRequest request = new ShowProductRequest();
        // 2、封装产品ID
        request.setProductId(productKey);
        // 3、调用API
        ShowProductResponse response = client.showProduct(request);
        // 4、解析结果集
        List<ServiceCapability> servicecapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(servicecapabilities)) {
            return Collections.emptyList();
        }
        return servicecapabilities;
    }

    /**
     * 根据设备ID绑定老人信息查询护理人员详情
     *
     * @param iotId 设备ID
     * @return 设备详情
     */
    @Override
    public List<Long> selectNursingIdsByIotIdWithElder(String iotId) {
        return deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
    }

    /**
     * 根据设备ID绑定床位信息查询护理人员详情
     *
     * @param iotId 设备ID
     * @return 设备详情
     */
    @Override
    public List<Long> selectNursingIdsByIotIdWithBed(String iotId) {
        return deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
    }
}